package com.tplhk.security.controller.charter4;

import com.google.code.kaptcha.Producer;
import com.tplhk.security.config.WebAuthenticationDetailsExt;
import com.tplhk.security.domain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName : LoginController
 * @Description : TODO
 * @Author : taiping
 * @Date: 2021/6/22 17:12
 **/
@RestController
@RequestMapping("/v4")
public class Hello4Controller {

    @Autowired
    Producer producer;

    @Autowired
    UserService userService;

    // /hello 是任何人都可以访问的接口
    @GetMapping("/hello")
    public String hello() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        WebAuthenticationDetailsExt details = (WebAuthenticationDetailsExt) authentication.getDetails();
        System.out.println(details);
        return "hello-v4";
    }

    ///admin/hello 是具有 admin 身份的人才能访问的接口
    @GetMapping("/admin/hello")
    public String admin() {
        return "admin-v4";
    }

    // /user/hello 是具有 user,admin 身份的人才能访问的接口
    @GetMapping("/user/hello")
    public String user() {
        return "user-v4";
    }

    @GetMapping("/vc.jpg")
    public void getVerifyCode(HttpServletResponse resp, HttpSession session) throws IOException {
        resp.setContentType("image/jpeg");
        String text = producer.createText();
        session.setAttribute("verify_code", text);
        BufferedImage image = producer.createImage(text);
        try (ServletOutputStream out = resp.getOutputStream()) {
            ImageIO.write(image, "jpg", out);
        }
    }

}
